package com.tourting.demo.service;

import com.tourting.demo.mapper.UserMapper;
import com.tourting.demo.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

@Service
public class UserService {

    private final Logger logger = LoggerFactory.getLogger(UserService.class);;

    @Autowired
    private UserMapper userMapper;

    public List<User> getAllUsers() {
        return userMapper.findAll();
    }

    public User getById(long id) {
        return userMapper.findById(id);
    }

    @Transactional
    public boolean save(User user) {
        user.setCreatedAt(new Date());
        try {
            userMapper.save(user);
            return true;
        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
            return false;
        }
    }

    @Transactional
    public boolean update(User user) {
        try {
            return userMapper.update(user) > 0;
        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
            return false;
        }
    }

    public boolean remove(long id) {
        return userMapper.remove(id) > 0;
    }
}
